using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TriUan.TriUanGame.GameComponents;
using TriUan.TriUanGame.GameComponents.Polygon;
using Microsoft.Xna.Framework;

namespace TriUan.SCSEngine.Utils
{
    public class CheckWin
    {
        private static CheckWin _instance = null;

        public static CheckWin Instance()
        {
            if (_instance == null)
                _instance = new CheckWin();
            return _instance;
        }

        private CheckWin()
        {
        }

        public bool IsCompleted(ITUPolygon pattern, ITUPolygonInfo patternInfo, Dictionary<ITUPolygon, ITUPieceInfo> pieces, float minDistance)
        {
            float squaredDistance = minDistance * minDistance;

            int nVertices = pattern.Vertices.Count;
            foreach (var piece in pieces)
            {
                nVertices += piece.Key.Vertices.Count;
            }

            List<Vector2> vertices = new List<Vector2>(nVertices);
            vertices.AddRange(VerticesTransform.Instance.Transform(pattern.Vertices, patternInfo.Position, pattern.Origin, patternInfo.Scale, 0f));
            foreach (var piece in pieces)
            {
                vertices.AddRange(VerticesTransform.Instance.Transform(piece.Key.Vertices, piece.Value.Position, piece.Key.Origin, piece.Value.Scale, piece.Value.Rotation));
            }

            int nRemoved = 0; 
            Vector2 firstVertex;
            do
            {
                if (vertices.Count <= 1)
                    return (vertices.Count < 1);

                nRemoved = 0;
                firstVertex = vertices.First();
                vertices.RemoveAt(0);

                for (int i = 0; i < vertices.Count; )
                {
                    if ((vertices[i] - (firstVertex)).LengthSquared() <= squaredDistance)
                    {
                        vertices.RemoveAt(i);
                        ++nRemoved;
                    }
                    else
                    {
                        ++i;
                    }
                }

            } while (nRemoved > 0);

            return false;
        }
    }
}
